﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class OnlyAuthenticated_OnlyManagers_EditModele : System.Web.UI.Page
{
    private string _currentUser;
    private readonly SqlConnection _connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    {
        _currentUser = LoginName.Page.User.Identity.Name;
        TextBoxDenumireModelEdit.Text = DropDownListModeleExistente.SelectedValue;

    }

    protected void AdaugaModelulButton_Click(object sender, EventArgs e)
    {
        if ((TextBoxTextModel.Text != string.Empty) & (TextBoxDenumireModel.Text != string.Empty) & (!TextBoxDenumireModel.Text.EndsWith(" ")) & (!TextBoxDenumireModel.Text.StartsWith(" ")))
        {
            string val = TextBoxTextModel.Text.Replace("\r\n", "<br />");//so that SQL gets the RETURN keys in text
            InsertRecord(TextBoxDenumireModel.Text, val, DropDownListSpecialitati.SelectedValue, _currentUser);

            TextBoxDenumireModel.Text = string.Empty;
            TextBoxTextModel.Text = string.Empty;
            this.RebindDropDowns();
        }
    }

    protected void DeleteButton_Click(object sender, EventArgs e)
    {
        DeleteRecord(DropDownListSpecialitati0.SelectedValue, DropDownListModeleExistente.SelectedValue);
        TextBoxDenumireModelEdit.Text = string.Empty;
        this.RebindDropDowns();
    }

    protected void SaveButton_Click(object sender, EventArgs e)
    {
        this.UpdateRecord(this.DropDownListSpecialitati0.SelectedValue,
            this.DropDownListModeleExistente.SelectedValue,
            this.TextBoxDenumireModelEdit.Text,
            this.HiddenModelText.Value);

        TextBoxDenumireModelEdit.Text = string.Empty;
        this.RebindDropDowns();

        this.SetUserLoginViewProperties();
    }

    private void InsertRecord(string numeModel, string textModel, string numeSpecialitate, string currentUser1)
    {
        string sqlStatementWithCheck = "IF NOT EXISTS (SELECT ID, NumeModel FROM DenumiriModele WHERE NumeModel = @numeModel) BEGIN INSERT INTO DenumiriModele (NumeModel, TextModel, Specialitate, UserEditor) VALUES (@numeModel, @textModel, @numeSpecialitate, @currentUser1) END";

        try
        {
            _connection.Open();
            SqlCommand cmd = new SqlCommand(sqlStatementWithCheck, _connection);
            cmd.Parameters.AddWithValue("@NumeModel", numeModel);
            cmd.Parameters.AddWithValue("@TextModel", textModel);
            cmd.Parameters.AddWithValue("@NumeSpecialitate", numeSpecialitate);
            cmd.Parameters.AddWithValue("@currentUser1", currentUser1);
            cmd.ExecuteNonQuery();
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Deletion/Insertion Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            _connection.Close();
        }

    }

    private void DeleteRecord(string selectedSpeciality, string modelName)
    {
        string deleteQuery = "Delete from DenumiriModele WHERE Specialitate = @Specialitate AND [NumeModel] = @modelName";

        if (!LoginName.Page.User.IsInRole("managers"))
        {
            deleteQuery += " AND UserEditor = @user";
        }

        try
        {
            _connection.Open();
            SqlCommand cmd = new SqlCommand(deleteQuery, _connection);
            cmd.Parameters.AddWithValue("@modelName", modelName);
            cmd.Parameters.AddWithValue("@Specialitate", selectedSpeciality);
            
            if (!LoginName.Page.User.IsInRole("managers"))
            {
                cmd.Parameters.AddWithValue("@user", _currentUser);
            }

            cmd.ExecuteNonQuery();
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Deletion/Insertion Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            _connection.Close();
        }
    }

    private void UpdateRecord(string selectedSpeciality, string selectedModel, string newModelName, string newModelText)
    {
        string updateQuery = "UPDATE DenumiriModele" +
                             " SET NumeModel = @newModelName, TextModel = @newModelText" +
                             " WHERE NumeModel = @selectedModel AND Specialitate = @selectedSpeciality";

        if (!LoginName.Page.User.IsInRole("managers"))
        {
            updateQuery += " AND UserEditor = @user";
        }

        try
        {
            _connection.Open();
            SqlCommand cmd = new SqlCommand(updateQuery, _connection);
            cmd.Parameters.AddWithValue("@newModelName", newModelName);
            cmd.Parameters.AddWithValue("@newModelText", newModelText);
            cmd.Parameters.AddWithValue("@selectedModel", selectedModel);
            cmd.Parameters.AddWithValue("@selectedSpeciality", selectedSpeciality);
            
            if (!LoginName.Page.User.IsInRole("managers"))
            {
                cmd.Parameters.AddWithValue("@user", _currentUser);
            } 

            cmd.ExecuteNonQuery();
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Update Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            _connection.Close();
        }
    }

    private void RebindDropDowns()
    {
        DropDownListSpecialitati.DataBind();
        DropDownListSpecialitati0.DataBind();
        DropDownListModeleExistente.DataBind();
    }

    private void SetUserLoginViewProperties()
    {
        //--this is for getting/setting values to/from components of an LoginView
        ContentPlaceHolder cp1 = (ContentPlaceHolder)Master.FindControl("MainContent");
        if (cp1 != null)
        {
            ContentPlaceHolder cp2 = (ContentPlaceHolder)Master.FindControl("GeneratorPageContent");
            if (cp2 != null)
            {
                Control ctl = (Control)LoginView3.FindControl("managers");
                if (ctl != null)
                {
                    Button but = (Button)ctl.FindControl("SaveButton");
                    if (but != null) but.Enabled = true;
                }
            }
        }
    }
}